package com.pg_chat.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.pg_chat.mapper.MessageMapper;
import com.pg_chat.model.MessagesEntity;
import com.pg_chat.utils.JsonUtil;
import com.pg_chat.utils.WordCloud;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service("chatService")
public class ChatServiceImpl implements ChatService{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    MessageMapper messageMapper;

    @Override
    public JSONObject historyMessage(String userId, String friendId,
                                 Date dateBegin, Date dateEnd){
        return getMsgFromDB(userId, friendId, dateBegin, dateEnd);
    }

    @Override
    public Object wordCloud(String roomId){
        WordCloud wc = new WordCloud();
        wc.createWordCloud("","");
        return  new Object();
    }

    @Override
    public Object messageFilter(String contentText){
        return new Object();
    }

    @Override
    public JSONObject chatRoomMsg(String userId, String friendId){
        //JSONObject json = new JSONObject();
        //设置时间，获取三天内的消息
        //LocalDateTime dateTime = LocalDateTime.now();
        //LocalDateTime beforeTime = dateTime.minusDays(3L);
        Date dateEnd = new Date();
        Date dateBefore = new Date(dateEnd.getTime()-259200000L);

        return getMsgFromDB(userId, friendId, dateBefore,dateEnd);

    }
    //"Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]"

    public JSONObject getMsgFromDB (String userId, String friendId
            , Date begin, Date end){
        JSONObject json = new JSONObject();

        Timestamp timeBegin = new Timestamp(begin.getTime());
        Timestamp timeEnd = new Timestamp(end.getTime());

        List<MessagesEntity> msgList = messageMapper
                .queryMessagesByTime(Integer.parseInt(userId),
                        Integer.parseInt(friendId),
                        timeBegin,timeEnd);

        if(msgList.size() > 0){
            JSONArray item = (JSONArray) JSONArray.toJSON(msgList);
            json.put("record",item);
            json.put("total",msgList.size());
        }else{
            json.put("record","null");
            json.put("total",0);
        }
        return json;

    }
}
